﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using HUGATE.ItemObject;
using CoreLibs;
using HUGATE.Utility;

namespace HUGATE.Item.Controls.Product
{

    /// <summary>
    /// Creator : thai huy
    /// Date    : 14/12/2010
    /// Desc    : Sản phẩm
    /// </summary>

    public partial class ProductEdit : System.Web.UI.UserControl
    {
        #region Variables

        private string strListPage = "ProductList.aspx";
        private string strProductID = "";
        private string proc = "ITEM_Product_ProductAttribute_Insert_Update";
        private string p_productID = "@ProductID";
        private string p_attributeID = "@AttributeID";
        private string p_valueID = "@ValueID";
        private string p_valueDes = "@ValueDescription";

        #endregion

        #region Properties

        public string ListPage
        {
            get { return strListPage; }
            set { strListPage = value; }
        }

        public string ProductID
        {
            get { return strProductID; }
            set { strProductID = value; }
        }

        #endregion

        #region Permissions

        String strAddPermission = "ITEM_Product_Add";
        String strEditPermission = "ITEM_Product_Edit";
        String strDeletePermission = "ITEM_Product_Delete";

        #endregion

        #region Support Functions

        /// <summary>
        /// Reset Control's data
        /// </summary>
        private void Clear()
        {
            txtObjectID.Text = "";
            txtObjectName.Text = "";
            //txtDesc.Text = "";   
            chkIsActived.Checked = false;
            //EnableControl(true);
        }
        /// <summary>
        /// Nạp dữ liệu vào Search Oject
        /// </summary>
        private void AssignedSOAssignSource(CommonControls.Search.SearchObject Oject, string ClCaption1, string ClCaption2, string ClID, string ClName1, string ClName2, string Store, string keyword)
        {
            Oject.ColumnCaption1 = ClCaption1;
            Oject.ColumnCaption2 = ClCaption2;
            Oject.ColumnID = ClID;
            Oject.ColumnName1 = ClName1;
            Oject.ColumnName2 = ClName2;
            Oject.StoreName = Store;
            Oject.ParaSearch1 = keyword;
            Oject.MultiSelect = false;
        }

        ///<summary>
        /// Gán default 
        ///</summary>
        private void AssignDefault(TextBox txtObject, Button btnObject, string value1, long value2)
        {
            txtObject.Text = value1;
            btnObject.CommandArgument = value2.ToString();
        }
        //<summary>
        /// Update Image 
        ///</summary>        
        private bool UpdateImage()
        {
            if (FileUpload1.HasFile)
                if (!Convert.ToString(ConfigurationManager.AppSettings["GEN_ImageFileTypeAllow"]).ToUpper().Contains(System.IO.Path.GetExtension(FileUpload1.FileName.ToUpper())))
                {
                    GlobalFunction.ShowMessageBox(Page, "Chọn tập tin có định dạng: " + Convert.ToString(ConfigurationManager.AppSettings["GEN_ImageFileTypeAllow"]).ToUpper());
                    return false;
                }

            string path = Globals.GetConfig("GEN_ImageDirectory") + "\\ERP\\Products\\";

            if (FileUpload1.HasFile)
            {
                int size;
                if (ConfigurationManager.AppSettings["GEN_MaxUploadImageFileSize"] != null)
                    size = Convert.ToInt32(ConfigurationManager.AppSettings["GEN_MaxUploadImageFileSize"]);
                else
                    size = 1024;

                HttpPostedFile file = FileUpload1.PostedFile;
                path += FileUpload1.FileName;

                if (file.ContentLength < size)
                    FileUpload1.SaveAs(path);
                else
                {
                    GlobalFunction.ShowMessageBox(Page, "Chọn tập tin có kích thước không vượt quá " + size.ToString() + " KB");
                    return false;
                }
            }
            else
                return false;

            return true;
        }
        /// <summary>
        ///Support  Update / Insert  
        /// </summary>
        private void CreateProc(string procductID, string attributeID, string valueID, string valueDescription)
        {
            IData objdata = CoreLibs.Data.CreateData();
            try
            {
                objdata.Connect();
                objdata.CreateNewStoredProcedure(proc);
                objdata.AddParameter(p_productID, procductID);
                objdata.AddParameter(p_attributeID, Convert.ToInt64(attributeID));
                objdata.AddParameter(p_valueID, Convert.ToInt64(valueID));
                objdata.AddParameter(p_valueDes, valueDescription);
                objdata.ExecNonQuery();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                objdata.Disconnect();
            }
        }
        /// <summary>
        /// Update / Insert  
        /// </summary>
        private void Insert_Update()
        {
            DataTable tbattribute = (DataTable)Session["ITEM_ProductProductAttributeData"];
            ITEMProductProductAttribute attribute = new ITEMProductProductAttribute();
            attribute.ProductID = Convert.ToString(Session["NewProductEditID"]);
            for (int i = 0; i < tbattribute.Rows.Count; i++)
            {
                attribute.AttributeID = Convert.ToString(tbattribute.Rows[i].ItemArray[1]);
                attribute.ValueID = Convert.ToString(tbattribute.Rows[i].ItemArray[3]);
                attribute.ValueDescription = Convert.ToString(tbattribute.Rows[i].ItemArray[5]);
                CreateProc(attribute.ProductID, attribute.AttributeID, attribute.ValueID, attribute.ValueDescription);
            }
        }
        private void Delete()
        {
            DataTable tbattributexoa = (DataTable)Session["ITEM_ProductProductAttributeData_xoa"];
            for (int i = 0; i < tbattributexoa.Rows.Count; i++)
            {
                ITEMProductProductAttribute product = new ITEMProductProductAttribute();
                product.ProductID = tbattributexoa.Rows[i].ItemArray[0].ToString();
                product.AttributeID = tbattributexoa.Rows[i].ItemArray[1].ToString();
                product.Delete();
            }

        }

        /// <summary>
        /// Load Object's info to controls
        /// </summary>
        public void LoadInfo()
        {
            ITEMProduct objProduct = new ITEMProduct();
            if (Session["NewProductEditID"] != null)
            {
                objProduct.ProductID = Convert.ToString(Session["NewProductEditID"]);
                if (objProduct.LoadInfo())
                {
                    chkAutoGen.Checked = false;
                    chkAutoGen.Visible = false;
                    txtObjectID.Enabled = false;
                    txtObjectID.Text = objProduct.ProductID.Trim();
                    txtObjectID.ReadOnly = true;
                    txtObjectName.Text = objProduct.ProductName.Trim();
                    AssignDefault(txtCategoryNameS, btnChooseCategory, objProduct.CategoryName, objProduct.CategoryID);
                    AssignDefault(txtManufacturerNameS, btnChooseManufacturer, objProduct.ManufacturerName, objProduct.ManufacturerID);
                    AssignDefault(txtUnitNameS, btnChooseUnit, objProduct.UnitName, objProduct.UnitID);
                    AssignDefault(txtProductStatusNameS, btnChoseProductStatus, objProduct.ProductStatusName, objProduct.ProductStatusID);
                    txtDescription.Text = objProduct.Description.Trim();
                    txtVAT.Text = Convert.ToString(Convert.ToDouble("0" + objProduct.VAT.ToString("#,##0")));
                    txtVATPercent.Text = objProduct.VATPercent.ToString();
                    chkIsSerial.Checked = objProduct.IsSerial;
                    chkIsActived.Checked = objProduct.IsActived;
                    string strFileName = "NoImage.jpg";
                    if (!string.IsNullOrEmpty(objProduct.Image.ToString()))
                        strFileName = objProduct.Image.ToString();
                    Session["image_insert"] = objProduct.Image.ToString();
                    imgsanpham.ImageUrl = Globals.ApplicationVRoot() + "/ImageHandler.ashx?m="
                        + WebLibs.EncryptDecrypt.EncryptRijinDael("ERP.Item.Product", Globals.GetConfig("SEC_FileSecureCode"))
                        + "&f=" + WebLibs.EncryptDecrypt.EncryptRijinDael(strFileName, Globals.GetConfig("SEC_FileSecureCode"));
                }
            }
            else
            {
                imgsanpham.ImageUrl = Globals.ApplicationVRoot() + "/ImageHandler.ashx?m="
                        + WebLibs.EncryptDecrypt.EncryptRijinDael("ERP.Item.Product", Globals.GetConfig("SEC_FileSecureCode"))
                        + "&f=" + WebLibs.EncryptDecrypt.EncryptRijinDael("NoImage.jpg", Globals.GetConfig("SEC_FileSecureCode"));
            }
        }

        #endregion

        #region Event Functions

        protected void Page_Load(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                Session["fullpath"] = FileUpload1.PostedFile.FileName;
            }
            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(Request["productid"]))
                {
                    Session["NewProductEditID"] = Request.QueryString["productid"].ToString();
                    txtObjectID.Attributes.Add("onblur", "CheckHTML('" + txtObjectID.ClientID + "');");
                    txtObjectName.Attributes.Add("onblur", "CheckHTML('" + txtObjectName.ClientID + "');");
                    txtDescription.Attributes.Add("onblur", "CheckHTML('" + txtDescription.ClientID + "');");
                }
                else
                    Session["NewProductEditID"] = null;

                LoadInfo();
                LoadCategoryTree();
                txtObjectID.MaxLength = 13;
                txtObjectName.MaxLength = 200;
                txtDescription.MaxLength = 2000;
                imgsanpham.Height = Convert.ToInt32(ConfigurationManager.AppSettings["ASS_ImageHeigh"].ToString());
                imgsanpham.Width = Convert.ToInt32(ConfigurationManager.AppSettings["ASS_ImageWidth"].ToString());

            }
            else
            {
                if (Session["fullpath"] != null)
                {
                    imgsanpham.ImageUrl = Convert.ToString(Session["fullpath"]);
                }
            }
            AssignedSOAssignSource(SOCategory, "Mã Ngành Hàng", "Tên Ngành Hàng", "CategoryID", "CategoryID", "CategoryName", "ITEM_Category_SRH", "@KeyWord");
            SOCategory.Selected += new EventHandler(SOCatagory_Selected);
            AssignedSOAssignSource(SOManufacturer, "Mã Nhà Sản Xuất", "Tên Nhà Sản Xuất", "ManufacturerID", "ManufacturerID", "ManufacturerName", "ITEM_Manufacturer_SRH", "@KeyWord");
            SOManufacturer.Selected += new EventHandler(SOManufacturer_Selected);
            AssignedSOAssignSource(SOUnit, "Mã Đơn Vị", "Tên Đơn Vị", "UnitID", "UnitID", "UnitName", "ITEM_Unit_SRH", "@KeyWord");
            SOUnit.Selected += new EventHandler(SOUnit_Selected);
            AssignedSOAssignSource(SOProductStatus, "Mã Trạng thái sản phẩm", "Tên Trạng thái sản phẩm", "ProductStatusID", "ProductStatusID", "ProductStatusName", "ITEM_ProductStatus_SRH", "@KeyWord");
            SOProductStatus.Selected += new EventHandler(SOProductStatus_Selected);


        }

        private void LoadCategoryTree()
        {
            ITEMCategory objCategory = new ITEMCategory();
            DataTable dtb = objCategory.SearchData(string.Empty);
            rtvCategory.Nodes.Clear();
            BuildCategoryTree(rtvCategory, dtb, 0);
            rtvCategory.ExpandAllNodes();
        }
        private void BuildCategoryTree(Telerik.Web.UI.RadTreeView rtv, DataTable dtb, int parentID)
        {
            DataRow[] drws = dtb.Select("ParentCategoryID=" + parentID);
            foreach (DataRow drw in drws)
            {
                Telerik.Web.UI.RadTreeNode rtn = new Telerik.Web.UI.RadTreeNode(drw["RefCategoryID"].ToString() + " - " + drw["CategoryName"].ToString(), drw["CategoryID"].ToString());
                rtv.Nodes.Add(rtn);
                BuildCategoryNode(rtn, dtb, Convert.ToInt32(drw["CategoryID"]));
            }
        }
        protected void rtvCategory_NodeClick(object sender, Telerik.Web.UI.RadTreeNodeEventArgs e)
        {
            txtCategoryNameS.Text = e.Node.Text;
            btnChooseCategory.CommandArgument = e.Node.Value;
            mpeCaragory.Hide();
            udpCategory.Update();
        }
        private void BuildCategoryNode(Telerik.Web.UI.RadTreeNode parentNode, DataTable dtb, int parentID)
        {
            DataRow[] drws = dtb.Select("ParentCategoryID=" + parentID);
            foreach (DataRow drw in drws)
            {
                Telerik.Web.UI.RadTreeNode rtn = new Telerik.Web.UI.RadTreeNode(drw["RefCategoryID"].ToString() + " - " + drw["CategoryName"].ToString(), drw["CategoryID"].ToString());
                parentNode.Nodes.Add(rtn);
                BuildCategoryNode(rtn, dtb, Convert.ToInt32(drw["CategoryID"]));
            }
        }
        private void SOCatagory_Selected(object sender, EventArgs e)
        {
            DataTable dt = SOCategory.dtResult;
            txtCategoryNameS.Text = dt.Rows[0]["CategoryName"].ToString();
            btnChooseCategory.CommandArgument = dt.Rows[0]["CategoryID"].ToString();
            mpeCaragory.Hide();
            udpCategory.Update();
        }
        private void SOManufacturer_Selected(object sender, EventArgs e)
        {
            DataTable dt = SOManufacturer.dtResult;
            txtManufacturerNameS.Text = dt.Rows[0]["ManufacturerName"].ToString();
            btnChooseManufacturer.CommandArgument = dt.Rows[0]["ManufacturerID"].ToString();
            mpeManufacturer.Hide();
            udpManufacturer.Update();
        }

        private void SOUnit_Selected(object sender, EventArgs e)
        {
            DataTable dt = SOUnit.dtResult;
            txtUnitNameS.Text = dt.Rows[0]["UnitName"].ToString();
            btnChooseUnit.CommandArgument = dt.Rows[0]["UnitID"].ToString();
            mpeUnit.Hide();
            udpUnit.Update();
        }
        private void SOProductStatus_Selected(object sender, EventArgs e)
        {
            DataTable dt = SOProductStatus.dtResult;
            txtProductStatusNameS.Text = dt.Rows[0]["ProductStatusName"].ToString();
            btnChoseProductStatus.CommandArgument = dt.Rows[0]["ProductStatusID"].ToString();
            mpeProductStatus.Hide();
            udpProductStatus.Update();
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            ITEMProduct objProduct = new ITEMProduct();
            if (chkAutoGen.Checked)
                objProduct.ProductID = "_?_AUTO_?_";
            else
            {
                if (txtObjectID.Text.Trim().Length <= 0)
                {
                    GlobalFunction.ShowMessageBox(Page, "Bạn cần phải nhập mã sản phẩm nếu không chọn tự động sinh!");
                    return;
                }
                else if (txtObjectID.Text.Trim().Length != 13)
                {
                    GlobalFunction.ShowMessageBox(Page, "Mã sản phẩm có chiều dài 13 ký tự!");
                    return;
                }
                objProduct.ProductID = txtObjectID.Text.Trim();
            }
            objProduct.ProductName = txtObjectName.Text.Trim();
            objProduct.CategoryID = Convert.ToInt64(btnChooseCategory.CommandArgument);
            objProduct.ManufacturerID = Convert.ToInt64(btnChooseManufacturer.CommandArgument);
            objProduct.UnitID = Convert.ToInt64(btnChooseUnit.CommandArgument);
            objProduct.ProductStatusID = Convert.ToInt64(btnChoseProductStatus.CommandArgument);

            if (UpdateImage())
            {
                objProduct.Image = FileUpload1.FileName;
            }
            else
            {
                objProduct.Image = Convert.ToString(Session["image_insert"]).Trim();
            }

            objProduct.Description = txtDescription.Text.Trim();
            objProduct.VAT = Convert.ToInt32(txtVAT.Text);
            objProduct.VATPercent = Convert.ToInt32(txtVATPercent.Text);
            objProduct.IsSerial = chkIsSerial.Checked;
            objProduct.IsActived = chkIsActived.Checked;
            objProduct.CreatedUser = "administrator";

            if (txtObjectID.ReadOnly == true)
            {
                if (objProduct.Update())
                {
                    //Insert_Update();
                    //Delete();
                    ProductAttributeInput1.SaveData();
                    GlobalFunction.ShowMessageBox(Page, string.Format(HUGATE.Utility.ResxManager.GetString("UpdateItemSuccessful"), HUGATE.Utility.ResxManager.GetString("ITEMProduct", true).ToLower()), HUGATE.Utility.ResxManager.GetString("MessageBox"), GlobalFunction.MessageBoxIcon.Information);
                }
                else
                    GlobalFunction.ShowMessageBox(Page, string.Format(HUGATE.Utility.ResxManager.GetString("CouldNotUpdateItem"), HUGATE.Utility.ResxManager.GetString("ITEMProduct", true).ToLower()), HUGATE.Utility.ResxManager.GetString("MessageBox"), GlobalFunction.MessageBoxIcon.WarningMessage);
            }
            else
            {
                int intInsertResult = objProduct.Insert();
                if (intInsertResult == 1)
                {
                    //Insert_Update();
                    ProductAttributeInput1.SaveData();
                    GlobalFunction.ShowMessageBox(Page, string.Format(HUGATE.Utility.ResxManager.GetString("InsertItemSuccessful"), HUGATE.Utility.ResxManager.GetString("ITEMProduct", true).ToLower()), HUGATE.Utility.ResxManager.GetString("MessageBox"), GlobalFunction.MessageBoxIcon.Information);
                }
                else if (intInsertResult == 0)
                {
                    GlobalFunction.ShowMessageBox(Page, "Mã sản phẩm đã tồn tại");
                }
                else
                    GlobalFunction.ShowMessageBox(Page, string.Format(HUGATE.Utility.ResxManager.GetString("CouldNotInsertItem"), HUGATE.Utility.ResxManager.GetString("ITEMProduct", true).ToLower()), HUGATE.Utility.ResxManager.GetString("MessageBox"), GlobalFunction.MessageBoxIcon.WarningMessage);
            }
        }
        protected void ibtClearCategory_Click(object sender, ImageClickEventArgs e)
        {
            txtCategoryNameS.Text = "";
            btnChooseCategory.CommandArgument = "";
            udpCategory.Update();
        }

        protected void ibtClearManufacturer_Click(object sender, ImageClickEventArgs e)
        {
            txtManufacturerNameS.Text = "";
            btnChooseManufacturer.CommandArgument = "";
            udpManufacturer.Update();
        }

        protected void ibtClearUnit_Click(object sender, ImageClickEventArgs e)
        {
            txtUnitNameS.Text = "";
            btnChooseUnit.CommandArgument = "";
            udpUnit.Update();
        }

        protected void ibtClearProductStatus_Click(object sender, ImageClickEventArgs e)
        {
            txtProductStatusNameS.Text = "";
            btnChoseProductStatus.CommandArgument = "";
            udpProductStatus.Update();
        }
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            Session["NewProductEditID"] = null;
            Session["image_insert"] = null;
            Session["fullpath"] = null;
            Response.Redirect(ListPage);
        }

        protected void txtObjectID_TextChanged(object sender, EventArgs e)
        {
            Session["NewProductEditID"] = txtObjectID.Text;
        }

        protected void imgdeleteimage_Click(object sender, ImageClickEventArgs e)
        {
            Session["image_insert"] = null;
            Session["fullpath"] = null;
            imgsanpham.ImageUrl = "";

        }

        #endregion

        protected void FileUpload1_Load(object sender, EventArgs e)
        {

        }

    }
}